<template>
  <div class="edit-subcribe-dialog">
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="true"
      :append-to-body="true"
      :class="{'mobile-el-dialog':showMobilePage}"
      class="subcribe-common-dialog small-common-dialog-size subcribe-dialog"
      @close="closeDialog"
      @open="openDialog"
    >
      <Title title="编辑预约" font-size="16px"/>
      <div class="tip">
        小提示：预约会自动检测该账号在所选预约时间内，是否存在其他预约。若需要检测竞品是否存在，需填写品牌标签和排他时间。
      </div>
      <el-form ref="subcribeRuleForm" :class="{ '': formDataIsValid }" :model="subcribeInfo" :rules="rules" :style="{maxHeight: maxHeight+'px'}" label-width="85px" label-position="right" class="lineHeight32 scroll">
        <el-form-item label="资源名称:" prop="id">
          <resource-info
            v-if="info"
            :resource-name="info.resourceName"
            :account-name-organization="info.accountNameOrganization"
            :account-name-platform="info.accountNamePlatform"
            :resource-id="info.resourceCode"
            account-belong-name="none"
          />
        </el-form-item>
        <el-form-item label="预约时间" prop="dateTime">
          <el-date-picker
            v-model="subcribeInfo.dateTime"
            :unlink-panels="true"
            :clearable="true"
            :editable="false"
            :picker-options="pickerOption"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            format="yyyy/MM/dd"
            size="small"
            @change="datePickerTime" />
        </el-form-item>
        <el-form-item label="预约名称" prop="subscribeName">
          <el-input
            v-model="subcribeInfo.subscribeName"
            placeholder="请输入至少三位字符"
            name="subscribeName"
            type="text"
            maxlength="50"
            @blur="nameBlur"
          />
        </el-form-item>
        <el-form-item label="投放类型" prop="type">
          <el-select v-model="subcribeInfo.type" placeholder="广告">
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value "
              size="small"/>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌名称" prop="brandName">
          <el-input
            v-model="subcribeInfo.brandName"
            placeholder="请输入品牌名称"
            name="brandName"
            type="text"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="下单形式" prop="orderForm">
          <el-select v-model="subcribeInfo.orderForm" placeholder="请选择下单形式" clearable >
            <el-option
              v-for="item in orderFormList"
              :key="item.id"
              :label="item.value"
              :value="item.id "
              :clearable = "true"
              size="small"/>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌标签" prop="demandCategory">
          <el-cascader
            ref="demandCategoryCascaber"
            v-model="subcribeInfo.demandCategory"
            :show-all-levels="false"
            :options="demandCategoryAry"
            :props="{
              multiple: false,
              checkStrictly: true,
              emitPath:false,
              value: 'id',
              label: 'name',
              children: 'item'
            }"
            filterable
            collapse-tags
            class="need-category-select"
            size="small"
            placeholder="请选择品牌标签"
            clearable
          />
        </el-form-item>
        <el-form-item label="排他时间" prop="exclusiveDateTime">
          <el-date-picker
            v-model="subcribeInfo.exclusiveDateTime"
            :unlink-panels="true"
            :clearable="true"
            :editable="false"
            :picker-options="pickerOption"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            format="yyyy/MM/dd"
            size="small"
            @change="exclusiveDatePickerTime" />
        </el-form-item>
        <el-form-item label="预约人" prop="subscribeUserIds">
          <mul-user-select :ids="ids" :options="subcribeInfo.subscribeUserIds" :limit-num="1" @postMessage="postMessage" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="mb20">
          <el-input
            :autosize="{minRows: 2, maxRows: 3}"
            v-model="subcribeInfo.remark"
            placeholder="请输入"
            resize="none"
            name="remark"
            type="textarea"
            maxlength="500"
            class="remark-input"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button class="ok" type="primary" @click="handelOk">确定</el-button>
        <el-button class="cancel-btn-style" type="info" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { editSubcribe, subcribeDetail } from '@/api/subcribe';
import MulUserSelect from '@/components/MulUserSelect';
import ResourceInfo from '@/components/ResourceInfo';
import subscribeDialog from '@/mixins/subscribeDialog';
import { mapState } from 'vuex';
export default {
  name: 'EditSubcribeDialog',
  components: { Title, MulUserSelect, ResourceInfo },
  mixins: [subscribeDialog],
  data() {
    return {
      pickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000;
        }
      },
      antiShakeTime: 0, // 防抖时间
      info: null,
      loading: false,
      isSubmit: false,
      dialogVisible: false,
      id: '',
      rules: {
        'id': [{ required: true, message: '', trigger: 'change' }],
        'subscribeName': [{ required: true, message: '请输入预约名称', trigger: 'change' }, { min: 3, message: '字符长度至少3位', trigger: 'blur' }],
        'dateTime': [{ required: true, message: '请选择起止日期', trigger: 'change' }]
      },
      resourceName: '',
      accountNameOrganization: '',
      subcribeInfo: {
        id: '',
        platformType: '', // 平台类型
        subscribeName: '',
        brandName: '',
        type: 1,
        orderForm: '',
        demandCategory: null,
        demandCategoryLabel: '',
        exclusiveDateTime: [],
        startDate: '',
        endDate: '',
        remark: '',
        dateTime: '',
        version: '',
        subscribeUserIds: []
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    handelOk() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const str = this.subcribeInfo.subscribeName.replace(/(^\s*)|(\s*$)/g, '');
      this.subcribeInfo.subscribeName = str;
      if (!this.formDataIsValid) {
        this.$refs.subcribeRuleForm.validate();
        this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
        return;
      }
      if (this.isSubmit) {
        return;
      }
      this.isSubmit = true;
      const params = this.getParams(true);
      editSubcribe(params, this.id).then(res => {
        this.isSubmit = false;
        if (res.code === 200) {
          // 请求后的逻辑
          this.checkDataStatus(res, true);
        }
      }).catch(e => {
        this.isSubmit = false;
      });
    },
    handleClose() {
      this.reservation = false;
      this.exclusive = false;
      this.$refs.subcribeRuleForm.resetFields();
      this.dialogVisible = false;
    },
    openDialog() {
      this.openDialogEvent(true);
    },
    initInfo(info) {
      this.info = info;
    },
    dateGetTime(time) {
      return time ? new Date(time.replace(/-/g, '/')).getTime() : '';
    },
    getSubcribeDetail(id) {
      subcribeDetail(id).then(res => {
        if (res.code === 200) {
          Object.assign(this.subcribeInfo, { ...res.data });
          this.subcribeInfo.startDate = this.dateGetTime(res.data.startDate);
          this.subcribeInfo.endDate = this.dateGetTime(res.data.endDate);
          this.subcribeInfo.exclusiveStartTime = this.dateGetTime(res.data.exclusiveStartTime);
          this.subcribeInfo.exclusiveEndTime = this.dateGetTime(res.data.exclusiveEndTime);
          this.subcribeInfo.dateTime = [this.subcribeInfo.startDate, this.subcribeInfo.endDate];
          this.subcribeInfo.exclusiveDateTime = this.subcribeInfo.exclusiveStartTime ? [this.subcribeInfo.exclusiveStartTime, this.subcribeInfo.exclusiveEndTime] : [];
          this.subcribeInfo.subscribeUserIds = [...res.data.subscribeUsers];
          this.orderPlatformId = res.data.orderPlatformId;
          this.getFormList(this.orderPlatformId);
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./subscribe.scss";
.tip {
  margin: 10px 0;
  padding: 6px 10px;
  color: #FFA340;
  line-height: 16px;
  font-size: 12px;
  background-color: #FFF8F1;
}
.subcribe-common-dialog {
  &.subcribe-dialog {
    &::v-deep {
      .el-form-item__label {
        color: #666;
      }
      .el-form-item:first-of-type{
        .el-form-item__label{
          color: #999;
        }
      }
    }
  }
}
</style>
<style lang="scss">
@import "./common.scss";
</style>
